package com.crazymakercircle.mutithread.basic.create.threadPool;

import com.crazymakercircle.util.Print;
import com.crazymakercircle.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.HashSet;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

import static com.crazymakercircle.util.ThreadUtil.sleepMilliSeconds;
import static com.crazymakercircle.util.ThreadUtil.sleepSeconds;

/**
 * @author ：weimo
 * @date ：Created in 2025/1/11
 * @description：newSignleThreadExecutor创建单线程化线程池
 */

@Slf4j
public class CreateThreadPoolDemo01 {

    //创建线程执行目标类

    static class TargetTask implements Runnable{

        static AtomicInteger taskNo=new AtomicInteger(1);
        private String taskName;

        public String getTaskName() {
            return taskName;
        }

        public void setTaskName(String taskName) {
            this.taskName = taskName;
        }

        public TargetTask(){
            taskName="task-"+taskNo.get();
            taskNo.incrementAndGet();
        }
        @Override
        public void run() {

            Print.tco("任务："+taskName+"开始运行");
            //sleepMilliSeconds(500);

        }
    }

    @Test
    public void testSignleThreadExecutor(){
        //创建只有一个线程的线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i=0;i<5;i++) {
            //executorService.execute(new TargetTask());
            executorService.submit(new TargetTask());


        }
        sleepSeconds(1000);
        executorService.shutdown();
    }

    @Test
    public void testNewFixedThreadPool(){

        log.info("=======创建固定数量的线程池");
        ExecutorService pool = Executors.newFixedThreadPool(3);

        for (int i=0;i<5;i++){
            pool.submit(new TargetTask());

        }
        sleepSeconds(1000);
        pool.shutdown();
    }

    @Test
    public  void testNewCacheThreadPool(){

        HashSet<String> set=new HashSet<>();
        log.info(">>>>>>>创建可缓存的线程池：");
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i=0;i<50;i++){
            TargetTask targetTask = new TargetTask();
            executorService.submit(targetTask);
            set.add(targetTask.getTaskName());
        }
        sleepSeconds(10);
        executorService.shutdown();

        System.out.println("本次的线程名称有:"+set.toString());
    }

    @Test
    public  void testNewScheduledThreadPool(){
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);

        for (int i=0;i<2;i++){
            scheduledExecutorService.scheduleAtFixedRate(new TargetTask(),0,500, TimeUnit.MILLISECONDS);

        }
        sleepSeconds(1000);
        scheduledExecutorService.shutdown();
    }





    @Test
    public void testSubmit2(){
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);

        Future<Integer> future = pool.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return RandomUtil.randInRange(200, 300);
            }

        });

        try {
            Integer integer = future.get();
            Print.tco("异步执行的结果是："+integer);
        }catch (InterruptedException e){
            Print.tco("异步调用被中断！！");
        }catch (ExecutionException e){
            Print.tco("异步调用过程中，发生了异常");
            e.printStackTrace();
        }
        sleepSeconds(10);
        pool.shutdown();

    }
    
    static class TargetTaskWithError extends  TargetTask{

        @Override
        public void run() {
            super.run();
            throw new RuntimeException(" Error from "+getTaskName());
        }
    }
    
    
    /**
     * 功能描述: submit返回的Future对象 捕获异常
     * @auther: zhangbanglong 
     * @date: 22:05 
     * @param 
     * @return 
    */
    
    @Test
    public  void testSubmit(){
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
        pool.execute(new TargetTaskWithError());

        Future<?> future = pool.submit(new TargetTaskWithError());

        try {
            if(future.get()==null){
                Print.tco("任务完成");
            }
        }catch (Exception e){
            Print.tco(e.getCause().getMessage());
            e.printStackTrace();
        }
        sleepSeconds(10);
        pool.shutdown();
    }


















}
